from django.core.validators import BaseValidator
from django.utils.deconstruct import deconstructible
from django.core.exceptions import ValidationError

from datetime import date


@deconstructible
class ValidatorModelBirth(BaseValidator):
    """
    验证: 字段必须符合要求, 且 年限[1900-至今] 月限[1-12]
    """
    message = '填写的出生日期不符合[YYYY-MM]格式要求'
    message_ = '填写的出生日期不正确'
    code = 'birth'

    def __init__(self, num):
        self.num = num

    def __call__(self, value):

        if len(value) > 7:
            raise ValidationError(self.message)

        results = value.split('-')

        if len(results) == 2:
            year_ = results[0]
            month_ = results[1]

            try:
                year = int(year_)
                month = int(month_)
            except Exception:
                raise ValidationError(self.message)

            if not (year > 1900 and year < (date.today().year + 1)):
                raise ValidationError(self.message_)

            if year == date.today().year:
                if not (month > 0 and month < (date.today().month + 1)):
                    raise ValidationError(self.message_)

            else:
                if not (month > 0 and month <= 12):
                    raise ValidationError(self.message_)
